package org.flowers.unbeaten.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.flowers.unbeaten.logging.aop.annotation.Logging;
import org.flowers.unbeaten.logging.aop.enums.BusinessType;
import org.flowers.unbeaten.util.CaptchaUtils;
import org.flowers.unbeaten.util.ServletUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @description 验证码生成控制器
 * @author RyanWang
 * @date 2021-07-20 10:43:44
 * @version 1.0
 */
@Api(tags = "后台系统-验证码管理")
@RestController
@RequestMapping("/captcha/captcha")
public class CaptchaController {

    public static final String captcha = "captcha";

    /**
     * @description 生成验证码
     * @return void
     * @author RyanWang
     * @date 2021-07-20 10:44:52
     * @version 1.0
     */
    @GetMapping("/captcha")
    @ApiOperation(value = "生成验证码接口")
    @Logging(title = "验证码管理", describe = "生成验证码", type = BusinessType.QUERY)
    public void captcha() throws IOException {

        // 创建输出流
        OutputStream outputStream = ServletUtils.getResponse().getOutputStream();
        // 获取session
        HttpSession session = ServletUtils.getRequest().getSession();
        // 获取验证码
        CaptchaUtils captchaUtils = new CaptchaUtils();
        String captcha = captchaUtils.getString();
        // 将验证码存入session，做登录验证
        session.removeAttribute(captcha);
        session.setAttribute("verifyCode", captcha);
        // 获取验证码图片
        BufferedImage image = captchaUtils.getImage();
        ImageIO.write(image, "png", outputStream);
        // 关流
        outputStream.flush();
        outputStream.close();
    }

}
